package com.wb.plugin;

import com.wb.plugin.enums.DataSourceType;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * @author 魏彪
 */
@Intercepts(value = {
        @Signature(type = Executor.class,
                method = "update",
                args = {
                        MappedStatement.class, Object.class
                }
        ),
        @Signature(type = Executor.class,
                method = "query",
                args = {
                        MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
                }
        ),
        @Signature(type = Executor.class,
                method = "query",
                args = {
                        MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, Cache.class
                }
        )
})
public class ReadWritePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        DataSourceType dataSourceType;
        // 类型为查询
        if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
            if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                // 使用主库：写库
                dataSourceType = DataSourceType.WRITE;
            } else {
                // 使用从库：读库
                dataSourceType = DataSourceType.READ;
            }
        } else {
            // 类型为增、删、改
            dataSourceType = DataSourceType.WRITE;
        }

        // 修改当前线程要选择的数据源的key
//        DataSource
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
